import axios from "axios"

import {getLoginUrl, getLoginData} from "@/modules/util"

//项目通用axios实例
const primaryAxiosInstance = axios.create({
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
    "X-Requested-With": "XMLHttpRequest",
  },
  timeout: 3000
})

//配置拦截器
primaryAxiosInstance.interceptors.response.use(
  response=>{
    getLoginData()
    return codeHandler(response)
  },
  e=>{
    return error(100, e)
  }
)

function codeHandler(response) {
  let data = response.data
  let code = data.resp_msg.msg_code
  if (code !== 400) {
    return response
  }
  let msg_error_code = data.resp_msg.msg_error.code
  switch (msg_error_code) {
    case 401:
      location.href = getLoginUrl()
      return error(401, "未登录状态")
    case 403:
      return error(403, "错误权限")
    default:
      return response
  }
}



function error(code = 666, message = "error") {
    return Promise.reject({ code, message })
}

//用于发起简单请求
window._axios = axios.create()

window.axios = primaryAxiosInstance

